<!--
 * @Author: Wangtao
 * @Date: 2020-09-21 09:55:09
 * @LastEditors: Wangtao
 * @LastEditTime: 2020-12-28 15:19:00
-->
<template>
  <continer :showPage="showPage">
    <template slot="search">
      <input
        ref="json-upload-input"
        class="json-upload-input"
        type="file"
        accept=".json"
        @change="uploadClick"
        v-show="false"
      />
      <QuickSearch
        :advForm="quickSearchForm"
        @QuickSearch="getIvrList"
      ></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini"  @click="getIvrList">查询</el-button>
      <el-button
        @click="handleAdd"
        size="mini"
        v-functions="['voice_navigation_insert']"
        >新增</el-button
      >
      <el-button
        size="mini"
        @click="handleExport"
        v-functions="['voice_navigation_import']"
        >导入</el-button
      >
    </template>
    <template slot="content">
      <configTable
        :headers="tableHeaders"
        :data="tableData"
        :pagingData="pagingData"
        @pageChange="pageChange"
        @pageSizeChange="pageSizeChange"
        @checkHeadersChange="checkHeadersChange"
        v-loading="showLoading"
        :headersConfig="false"
        ref="configTabel"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              :resizable="false"
              :prop="item.prop"
              :label="item.label"
              :key="item.label + index"
              :sortable="item.sortable"
              :show-overflow-tooltip="true"
              v-if="
                item.show &&
                item.prop !== 'oprate' &&
                item.prop !== 'status' &&
                item.prop !== 'updateUser' &&
                item.prop !== 'numbers'
              "
            >
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'updateUser' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span :key="item.prop">{{ scope.row.updateAgent }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'status' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span :key="item.prop"
                  ><i
                    :class="{
                      V7_iconfont: true,
                      V7_iconV7tubiao_dian: true,
                      enable: scope.row.status === 'enable',
                      status: true
                    }"
                  ></i
                  >{{ scope.row | getIvrStatus }}</span
                >
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'numbers' && item.show"
              :key="item.label + index"
              :show-overflow-tooltip="true"
              :sortable="item.sortable"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.numbers | getNumberText }}</span>
              </template>
            </u-table-column>
            <u-table-column
              :label="item.label"
              v-if="item.prop === 'oprate' && item.show"
              :key="item.label + index"
              :sortable="item.sortable"
              fixed="right"
              :width="120"
            >
              <template slot-scope="scope">
                <span
                  class="oprate"
                  @click="handleEdit(scope)"
                  v-functions="['voice_navigation_edit']"
                  >编辑</span
                >
                <span
                  class="oprate"
                  @click="downloadData(scope.row)"
                  v-functions="['voice_navigation_export']"
                  >导出</span
                >
                <span
                  v-functions="['voice_navigation_enableOrDisable']"
                  :class="{
                    oprate: true,
                    isEnable: scope.row.status === 'enable'
                  }"
                  @click="handleStatus(scope)"
                  >{{ scope.row | getIvrOprateStatus }}</span
                >
                <span
                  class="oprate delete"
                  @click="hangleDelete(scope.row)"
                  v-functions="['voice_navigation_delete']"
                  >删除</span
                >
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
    </template>
    <template slot="page">
      <flow-chart
        :ivrData="ivrData"
        @ivrSaveSuccess="ivrSaveSuccess"
        @pageBack="pageBack"
      ></flow-chart>
    </template>
  </continer>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/configCommon/table.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import FlowChart from './flowChart/index.vue'
import { IvrModule } from '@/store/modules/config/ivr'
import { ElMessage } from 'element-ui/types/message'
import { ElMessageBoxShortcutMethod } from 'element-ui/types/message-box'
import { Store } from 'vuex/types'
import { IvrData, PagingData, TabelHeaders } from './types/index'
@Component({
  name: 'ServiceNumber',
  components: { continer, configTable, FlowChart, QuickSearch },
  filters: {
    getIvrStatus (item) {
      if (item.status === 'enable') {
        return '启用'
      } else {
        return '停用'
      }
    },
    getIvrOprateStatus (item) {
      if (item.status === 'enable') {
        return '停用'
      } else {
        return '启用'
      }
    },
    getNumberText (numbers) {
      return numbers.join(',')
    }
  }
})
export default class extends Vue {
  private $message: ElMessage | undefined
  private $confirm: ElMessageBoxShortcutMethod | undefined
  private $store: Store<any> | undefined
  private showLoading: boolean = false

  // 语音导航数据
  private ivrData: IvrData = {}

  private mounted (): void {
    this.getIvrList()
  }

  // 详情控制

  private showPage: boolean = false

  private pagingData: PagingData = { total: 0, limit: 10, page: 1 }

  private tableHeaders: TabelHeaders[] = [
    {
      label: '名称',
      prop: 'name'
    },
    {
      label: '编号',
      prop: '_id'
    },
    {
      label: '服务号',
      prop: 'numbers'
    },
    {
      label: '备注',
      prop: 'remark'
    },
    {
      label: '状态',
      prop: 'status'
    },
    {
      label: '修改人',
      prop: 'updateAgent'
    },
    {
      label: '最后修改时间',
      prop: 'updateTime',
      sortable: true
    },
    {
      label: '操作',
      prop: 'oprate',
      disenable: true
    }
  ]

  private checkHeaders: TabelHeaders[] = []
  private tableData: IvrData[] = []

  private stateOptions = [{
    name: '全部',
    _id: ''
  }, {
    name: '停用',
    _id: 'disable'
  }, {
    name: '启用',
    _id: 'enable'
  }]

  private quickSearchForm = { // 快捷检索数据（时间条件，类型）
    form: {
      name: '',
      status: ''
    },
    advSearchOptions: [ // 快捷检索的数据(语音文件名称)
      { label: '语音导航', inputType: 'input', placeholder: '请输入语音导航名称', name: 'name', clearable: true },
      { label: '状态', inputType: 'select', clearable: true, selectData: this.stateOptions, name: 'status' }
    ]
  }

  private pageChange (page: number): void {
    this.pagingData.page = page
    this.getIvrList()
  }

  private pageSizeChange (size: number): void {
    this.pagingData.page = 1
    this.pagingData.limit = size
    this.getIvrList()
  }

  private handleEdit (scope): void {
    this.ivrData = scope.row
    this.showPage = true
  }

  private checkHeadersChange (checkList): void {
    this.$set(this, 'checkHeaders', checkList)
  }

  private pageBack (): void {
    (this.$confirm as ElMessageBoxShortcutMethod)('您没有进行保存操作, 确定离开页面吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      this.showPage = false
    })
  }

  private handleAdd (): void {
    this.ivrData = {}
    this.showPage = true
  }

  private getIvrList (): void {
    this.showLoading = true
    const actionData = Object.assign({ limit: this.pagingData.limit, page: this.pagingData.page }, this.quickSearchForm.form)
    const data = { url: '/call/action/config/ivr/query', method: 'POST', data: actionData }
    IvrModule.IvrCommonAction(data).then((res: any) => {
      if (res && res.list) {
        const resList = res.list || []
        if (resList.length === 0) {
          const page = Math.ceil(res.count / this.pagingData.limit)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.pagingData.page = 1
          } else { // 删除到最后一个回到上一页
            this.pagingData.page = page
            this.getIvrList()
            return false
          }
        }
        resList.forEach((item: any) => {
          const agentObj = (this.$store as Store<any>).state.common.publicCache.userListObj[item.updateUser]
          item.updateAgent = agentObj ? `${agentObj.agentName}【${agentObj.agentNumber}】` : '--'
        })
        this.tableData = resList
        this.pagingData.total = res.count || 0
      }
      this.showLoading = false
    })
  }

  private downloadData (data): void {
    (this.$confirm as ElMessageBoxShortcutMethod)('确定要下载该语音导航数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      const ivrData: IvrData = {}
      ivrData.lineList = data.lineList
      ivrData.name = new Date().getTime() + ''
      ivrData.nodeList = data.nodeList
      ivrData.remark = data.remark
      const datastr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(ivrData, null, '\t'));
      const downloadAnchorNode = document.createElement('a')
      downloadAnchorNode.setAttribute('href', datastr);
      downloadAnchorNode.setAttribute('download', data.name + '.json')
      downloadAnchorNode.click();
      downloadAnchorNode.remove();
      (this.$message as ElMessage).success('正在下载中,请稍后...')
    })
  }

  private hangleDelete (ivrData: IvrData): void {
    (this.$confirm as ElMessageBoxShortcutMethod)('确定要删除语音导航吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      const data = { url: '/call/action/config/ivr/delete', method: 'POST', data: { _id: ivrData._id } }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        this.pagingData.page = 1
        this.getIvrList()
      })
    })
  }

  private handleExport (): void {
    (this.$refs as any)['json-upload-input'].click()
  }

  private uploadClick (e: Event): void {
    const files = (e.target as any).files
    if (files) {
      const rawFile = files[0] // only use files[0]
      const reader = new FileReader()
      reader.onload = (evt) => {
        let jsonData: any = (evt.target as FileReader).result
        jsonData = JSON.parse(jsonData)
        const data = { url: '/call/action/config/ivr/create', method: 'POST', data: jsonData }
        IvrModule.IvrCommonAction(data).then((res: any) => {
          (this.$refs as any)['json-upload-input'].value = ''
          console.log((this.$refs as any)['json-upload-input'])
          if (res.success) {
            this.pageChange(1);
            (this.$message as ElMessage).success('导入成功')
          }
        })
      }
      reader.readAsText(rawFile)
    }
  }

  private handleStatus ({ row }): void {
    let setStatus
    let tipText
    if (row.status === 'enable') {
      tipText = '停用'
      setStatus = 'disable'
    } else {
      tipText = '启用'
      setStatus = 'enable'
    }
    (this.$confirm as ElMessageBoxShortcutMethod)(`确定要${tipText}【${row.name}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      const query = { _id: row._id, status: setStatus }
      const data = { url: '/call/action/config/ivr/status', method: 'POST', data: query }
      IvrModule.IvrCommonAction(data).then((res: any) => {
        if (res.success) {
          row.status = setStatus;
          (this.$message as ElMessage).success(`${tipText}成功`)
        }
      })
    })
  }

  private ivrSaveSuccess (type): void {
    this.showPage = false
    this.pageChange(1)
  }
}
</script>

<style lang="stylus" scoped>
.status
  font-size 14px
  color $c-danger
.enable
  color $c-green
.oprate
  color $c-main
  margin-right 10px
  cursor pointer
.isEnable
  color $c-danger
.oprate:hover
  opacity 0.8
.delete
  color $c-danger
</style>
